<?php

namespace app\admin\controller;

use app\models\{AgentArea, Agent as Agents, Region, AgentLog, Subcate, Cate, Product, Riderlist, RiderStreet, Withdraw, Promo, Order, Douyin, Pkey, Coupon};
use think\Db;
use think\Validate;
use EasyWeChat\Factory;


class Agent extends Base
{


    public function agentarea_quan()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'ploygongeo' => 'require'
            ], [
                'id.require' => 'ID不能为空',
                'ploygongeo.require' => '坐标集不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $model = new AgentArea();
            //查找店铺名称、账号是否已经被使用
            $have = $model->where(['id' => $data['id'], 'type' => 5])->find();
            if (empty($have)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请重试']);
            }
            $text = null;
            if (count($data['ploygongeo']) > 0) {
                $data['ploygongeo'][] = $data['ploygongeo'][0];
            }
            $ploygongeoarr = [];
            //范围验证查询
            $arrfw = [];
            foreach ($data['ploygongeo'] as $ploygon) {
                # code...
                if (count($ploygon) != 2) {
                    return json(['code' => 1, 'data' => [], 'msg' => '数据错误，请重试']);
                }
                $arrfw[] = implode(',', $ploygon);
                $ploygon = implode(' ', $ploygon);
                $ploygongeoarr[] = $ploygon;
            }
            //需要查询的数组
            $key = env('map.key');
            // foreach ($arrfw as $arrfws) {
            //     $url = 'https://restapi.amap.com/v3/geocode/regeo';
            //     $res = api_curl($url, ['location' => $arrfws, 'key' => $key, 'extensions' => 'base']);
            //     if ($res['status'] == 1 && !empty($res['regeocode']['addressComponent']['adcode'])) {
            //     } else {
            //         return json(['code' => 1, 'data' => [], 'msg' => '坐标错误或超出范围，请适当调整后再试']);
            //     }
            // }
            $ploygongeoarr = implode(',', $ploygongeoarr);
            $text = 'POLYGON((' . $ploygongeoarr . '))';
            //查询重叠数值
            $sql =  "st_intersects(ST_PolygonFromText(ploygongeo),ST_PolygonFromText('" . $text . "')) = 1";
            $agentarea = (new AgentArea())->where('id', '<>', $data['id'])->where('type', 5)->where($sql)->find();
            if (!empty($agentarea)) {
                return json(['code' => 1, 'data' => [], 'msg' => '该区域与已分配区域重叠，请检查后重新划分']);
            }
            $res = $model->allowfield(true)->save(['ploygongeo' => $text], ['id' => $data['id']]);
            if ($res) {
                return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new AgentArea();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->field('substring(ploygongeo,10,length(ploygongeo)-11) as ploygongeo,id')->find();
            $arr = [];
            if ($row) {
                $row['ploygongeo'] = explode(',', $row['ploygongeo']) ?? [];
                $row['ploygongeo'] = array_slice($row['ploygongeo'], 0, -1);
                foreach ($row['ploygongeo'] as $key => $ploygongeo) {
                    $ploygongeo = explode(' ', $ploygongeo) ?? [];
                    $arr[] = $ploygongeo;
                }
            }
            $istrue = 1;
            foreach ($arr as $arrs) {
                if (count($arrs) != 2 && $istrue == 1) {
                    $istrue = 2;
                }
            }
            if ($istrue == 2) {
                $arr = [];
            }
            //获取全部区域
            $model = new AgentArea();
            $lists = $model->where('type', 5)->where('id', '<>', $id)->field('substring(ploygongeo,10,length(ploygongeo)-11) as ploygongeo,id')->select();
            $arr2 = [];
            foreach ($lists as $list) {
                $list['ploygongeo'] = explode(',', $list['ploygongeo']) ?? [];
                $list['ploygongeo'] = array_slice($list['ploygongeo'], 0, -1);
                foreach ($list['ploygongeo'] as $key => $ploygongeos) {
                    $ploygongeos = explode(' ', $ploygongeos) ?? [];
                    $arr2[$list['id']][] = $ploygongeos;
                }
            }
            array_multisort($arr2);
            return view('', [
                'row' => $row,
                'arr' => $arr,
                'arr2' => $arr2
            ]);
        }
    }

    public function quhuaall()
    {
        $model = new AgentArea();
        $lists = $model->where('type', 5)->field('substring(ploygongeo,10,length(ploygongeo)-11) as ploygongeo,id')->select();
        $arr = [];
        foreach ($lists as $list) {
            $list['ploygongeo'] = explode(',', $list['ploygongeo']) ?? [];
            $list['ploygongeo'] = array_slice($list['ploygongeo'], 0, -1);
            foreach ($list['ploygongeo'] as $key => $ploygongeo) {
                $ploygongeo = explode(' ', $ploygongeo) ?? [];
                $arr[$list['id']][] = $ploygongeo;
            }
        }
        array_multisort($arr);
        return view('', [
            'arr' => $arr
        ]);
    }

    public function index_exc()
    {
        if ($this->request->isAjax()) {
            $data = input();
            $validate = new Validate([
                'id' => 'require',
            ], [
                'id.require' => 'ID不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            //查询代理是否已存在
            $agent = (new Agents())->where(['id' => $data['id'], 'status' => 1])->find();
            if (empty($agent)) {
                return json(['code' => 1, 'msg' =>  '代理不存在或已冻结']);
            }
            $cates = (new Cate())->where('isshow', 1)->order('sort desc')->select();
            //根据分类导入
            $text = '';
            try {

                foreach ($cates as $cate) {
                    //查找子分类
                    $subcates = (new Subcate())->where(['isshow' => 1, 'cate' => $cate['id'], 'agentid' => 0])->order('sort desc')->select();
                    foreach ($subcates as $subcate) {
                        /************1、判断子分类是否需要导入*************/
                        $sub = (new Subcate())->whereOr(function ($query) use ($subcate, $data) {
                            $query->where(['isshow' => 1, 'topid' => $subcate['id'], 'agentid' => $data['id']]);
                        })->whereOr(function ($query) use ($subcate, $data) {
                            $query->where(['isshow' => 1, 'name' => $subcate['name'], 'agentid' => $data['id']]);
                        })->find();
                        //先导入子分类获取已导入的分类ID
                        if (empty($sub)) {
                            $agentsub = [
                                'agentid' => $data['id'],
                                'cate' => $subcate['cate'],
                                'name' => $subcate['name'],
                                'isshow' => $subcate['isshow'],
                                'images' => $subcate['images'],
                                'sort' => $subcate['sort'],
                                'topid' => $subcate['id'],
                            ];
                            $subcateid = (new Subcate())->insertGetId($agentsub);
                            if (!$subcateid) {
                                $text = $text . '子分类[' . $subcate['name'] . ']导入失败<br/>';
                                continue;
                            }
                        } else {
                            $subcateid = $sub['id'];
                        }
                        //查找子分类下系统产品
                        $products = (new Product())->where(['subcate' => $subcate['id'], 'agentid' => 0, 'isdel' => 1, 'isshow' => 1])->select();
                        /************1、判断产品是否需要导入*************/
                        foreach ($products as $product) {
                            $sproduct = (new Product())
                                ->whereOr(function ($query) use ($product, $data) {
                                    $query->where(['isshow' => 1, 'topid' => $product['id'], 'agentid' => $data['id'], 'isdel' => 1]);
                                })->whereOr(function ($query) use ($product, $data) {
                                    $query->where(['isshow' => 1, 'title' => $product['title'], 'agentid' => $data['id'], 'isdel' => 1]);
                                })->find();
                            //不存在就导入产品
                            if (empty($sproduct)) {
                                $drpro = [
                                    'agentid' => $data['id'],
                                    'cate' => $subcate['cate'],
                                    'type' =>  $product['type'],
                                    'subcate' => $subcateid,
                                    'price' => $product['price'],
                                    'title' => $product['title'],
                                    'descs' => $product['descs'],
                                    'images' => $product['images'],
                                    'ishot' => $product['ishot'],
                                    'isshow' => $product['isshow'],
                                    'sort' => $product['sort'],
                                    'topid' => $product['id'],
                                ];
                                $res = (new Product())->allowfield(true)->save($drpro);
                                if (!$res) {
                                    $text = $text . '产品[' . $product['title'] . ']导入失败<br/>';
                                    continue;
                                }
                            }
                        }
                    }
                }
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'msg' => '操作成功']);
        }
    }

    public function promo()
    {
        if ($this->request->isAjax()) {
            $model = new Promo();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['title', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['agentid'])) {
                $where[] = ['agentid', '=', $post['agentid']];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            if (!empty($post['type'])) {
                $where[] = ['type', '=', $post['type']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['agent_name'] = '系统';
                if ($lists['agentid'] > 0) {
                    $lists['agent_name'] = (new Agents())->where(['id' => $lists['agentid']])->value('nickname') ?? '';
                }
                $lists['people'] = (new Pkey())->where('promoid', $lists['id'])->count();
                $lists['peoples'] = (new Pkey())->where(['promoid' => $lists['id'], 'status' => 2])->count();
                $lists['peopless'] = (new Pkey())->where(['promoid' => $lists['id'], 'status' => 3])->count();
                $lists['btmoney'] = (new Coupon())->where(['promo' => $lists['id']])->sum('btmoney');
                $lists['btmoney1'] = (new Coupon())->where(['promo' => $lists['id'], 'status' => 1])->sum('btmoney');
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }

    public function promo_alert()
    {
        $id = $this->request->get('id/d', 0);
        $row = (new Promo())->where(['id' => $id])->find();
        if (empty($row)) {
            return view();
        }
        //如果图片都存在则生成合成图片
        $names = './uploads/hecheng/alpha_image' . $id . '.jpg';
        $hecheng = url($names, '', '', true);
        $name = 'promo' . $id . '.png';
        $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/promo/";
        if (!file_exists($path . $names)) {
            //微信小程序码
            try {
                if (!is_dir($path)) {
                    mkdir($path, 0777, true);
                }
                $config = config('wechat.');
                $app = Factory::miniProgram($config);
                $rm = $app->app_code->getUnlimit('promoid=' . $id, [
                    'page'  => 'pages/index/getCoupon',
                    'auto_color' => false,
                    'width' => 400
                ]);
                if ($rm instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                    $rm->save($path, $name);
                }
            } catch (\Exception $e) {
                //dump($e->getMessage());
            }
            //字节小程序码
            $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/zijie/";
            try {
                $res = (new Douyin())->qrcode('pages/index/getCoupon?scene=promoid=' . $id);
                if ($res) {
                    file_put_contents($path . $name, $res);
                }
            } catch (\Exception $e) {
                // $this->result([], 1, '获取信息错误,请重试');
            }
            try {
                $image1 = \think\Image::open('./uploads/promo/' . $name);
                $image1->thumb(190, 190)->save('./uploads/promo/m_' . $name);
                $image2 = \think\Image::open('./uploads/zijie/' . $name);
                $image2->thumb(190, 190)->save('./uploads/zijie/m_' . $name);
                $image = \think\Image::open('./true.jpg');
                $image->water('./uploads/promo/m_' . $name, [273, 175], 100)->save($names);
                $image->water('./uploads/zijie/m_' . $name, [48, 175], 100)->save($names);
            } catch (\Exception $e) {
                // $this->result([], 1, '获取信息错误,请重试');
            }
        }
        return view('', [
            'url' => $hecheng
        ]);
    }

    public function keys()
    {
        if ($this->request->isAjax()) {
            $model = new Pkey();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['id', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['code'])) {
                $where[] = ['code', 'like', '%' . $post['code'] . '%'];
            }
            if (!empty($post['promoid'])) {
                $where[] = ['promoid', '=', $post['promoid']];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['btmoney'] = (new Coupon())->where(['keyid' => $lists['id']])->sum('btmoney');
                $lists['btmoney1'] = (new Coupon())->where(['keyid' => $lists['id'], 'status' => 1])->sum('btmoney');
                //查询代理
                $agentid = (new Promo())->where('id', $lists['promoid'])->value('agentid');
                if ($agentid <= 0) {
                    $lists['agent_name'] = '平台';
                } else {
                    $lists['agent_name'] = (new Agents())->where('id', $agentid)->value('nickname');
                }
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }

    public function keys_status()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Pkey();
            $ids = [];
            if (is_array($id)) {
                foreach ($id as $idd) {
                    $cate = $model->where(['id' => $idd, 'status' => 1])->find();
                    if (!empty($cate)) {
                        $ids[] = $idd;
                    }
                }
            } else {
                $ids[] = $id;
            }
            if (count($ids) <= 0) {
                return json(['code' => 1, 'data' => [], 'msg' => '无可操作内容']);
            }

            Db::startTrans();
            try {
                $model->where(['id' => $ids])->update(['status' => 3]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function promo_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'agentid' => 'require',
                'money' => 'require|gt:0'
            ], [
                'title.require' => '活动不能为空',
                'agentid.require' => '代理不能为空',
                'money.require' => '支付金额必须填写',
                'money.gt' => '支付金额必须大于0',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if (!is_array($data['coupon'])) {
                return json(['code' => 1, 'msg' => '优惠券数据出错']);
            }
            if (!empty($data['code']) && (!preg_match('/^[A-Z]+$/', $data['code']) || mb_strlen($data['code']) > 4)) {
                return json(['code' => 1, 'msg' => '编码前缀请输入1-4位大写字母']);
            }
            $data['coupon'] = json_encode($data['coupon'], true);
            if (empty($data['id'])) {
                $res = (new Promo())->allowfield(true)->save($data);
            } else {
                $res = (new Promo())->allowfield(true)->save($data, ['id' => $data['id']]);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Promo())->where(['id' => $id])->find();
            if ($row) {
                $row['coupon'] = json_decode($row['coupon'], true);
            }
            return view('', [
                'row' => $row,
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }

    public function promo_edit2()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'money' => 'require|gt:0'
            ], [
                'title.require' => '活动不能为空',
                'money.require' => '支付金额必须填写',
                'money.gt' => '支付金额必须大于0',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if (!is_array($data['coupon'])) {
                return json(['code' => 1, 'msg' => '优惠券数据出错']);
            }
            $data['agentid'] = 0;
            $data['type'] = 2;
            $data['coupon'] = json_encode($data['coupon'], true);
            if (empty($data['id'])) {
                $res = (new Promo())->allowfield(true)->save($data);
            } else {
                $res = (new Promo())->allowfield(true)->save($data, ['id' => $data['id']]);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Promo())->where(['id' => $id])->find();
            if ($row) {
                $row['coupon'] = json_decode($row['coupon'], true);
            }
            return view('', [
                'row' => $row
            ]);
        }
    }

    public function promo_key()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'knumber' => 'require|gt:0'
            ], [
                'id.require' => 'ID不能为空',
                'knumber.require' => '数量不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            $data['knumber'] = (int)$data['knumber'];
            if ($data['knumber'] > 1000) {
                return json(['code' => 1, 'data' => [], 'msg' => '为避免时间过久生成失败，单次生成数量不能超过1000']);
            }
            $row = (new Promo())->where(['id' => $data['id'], 'type' => 1])->find();
            if (empty($row)) {
                return json(['code' => 1, 'data' => [], 'msg' => '项目不存在，请重试']);
            }
            if ($row['type'] != 1) {
                return json(['code' => 1, 'data' => [], 'msg' => '非兑换码套餐不能生成兑换码']);
            }
            if ($row['status'] != 1) {
                return json(['code' => 1, 'data' => [], 'msg' => '活动已结束，无法继续生成']);
            }
            if (!empty($row['code']) && (!preg_match('/^[A-Z]+$/', $row['code']) || mb_strlen($row['code']) > 4)) {
                return json(['code' => 1, 'msg' => '项目编码前缀非1-4位大写字母，请重新设置']);
            }
            for ($i = 1; $i <= $data['knumber']; $i++) {
                $code = rekey(new Pkey(), $row['code']);
                if (empty($code)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '生成' . ($i - 1) . '个，第' . $i . '个后生成失败']);
                }
                $res = (new Pkey())->allowfield(true)->save(['promoid' => $row['id'], 'code' => $code]);
                if (!$res) {
                    return json(['code' => 1, 'data' => [], 'msg' => '生成' . ($i - 1) . '个，第' . $i . '个后生成失败']);
                }
            }
            return json(['code' => 200, 'data' => [], 'msg' => '生成成功,请兑换码列表内查看']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
    }


    public function withdraw()
    {
        if ($this->request->isAjax()) {
            $model = new Withdraw();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['name|cards', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['agentid'])) {
                $where[] = ['user_id', 'in', $post['agentid']];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['agent_name'] = (new Agents())->where(['id' => $lists['user_id']])->value('nickname') ?? '';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }

    public function withdraw_status()
    {
        $id = input('id');
        $status = input('status/s', '0');
        $text = input('text');
        if (!empty($id)) {
            if ($status != 2 && $status != 3) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据状态错误']);
            }
            $model = new Withdraw();
            $cate = $model->where(['id' => $id])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            if ($cate['status'] != 1) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据已审核，无需重复审核']);
            }
            dump($text);
            if ($status == 3 && empty($text)) {
                return json(['code' => 1, 'data' => [], 'msg' => '请填写驳回理由']);
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update(['status' => $status, 'text' => $text]);
                if ($status == 3) {
                    (new Agents())->MoneyEdit($cate['user_id'], 3, $cate['money'], '提现驳回', $cate['id']);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function rider()
    {
        if ($this->request->isAjax()) {
            $model = new Riderlist();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['mobile|name|cards', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['agentid'])) {
                $riderid = (new RiderStreet())->distinct(true)->where(['agentid' => $post['agentid']])->column('riderid');
                $where[] = ['id', 'in', $riderid];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            if (!empty($post['street'])) {
                $where[] = ['street', '=', $post['street']];
            } elseif (!empty($post['area'])) {
                $where[] = ['area', '=', $post['area']];
            } elseif (!empty($post['city'])) {
                $where[] = ['city', '=', $post['city']];
            } elseif (!empty($post['province'])) {
                $where[] = ['province', '=', $post['province']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['count']  = (new Order())->where(['orderid' => $lists['id'], 'status' => 4])->count();
                $lists['total']  = (new Order())->where(['orderid' => $lists['id'], 'status' => 4])->sum('total');
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'province' => (new Region())->where(['level' => 1])->select(),
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }


    public function rider_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
            ], [
                'id.require' => 'ID不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            } elseif (isset($data['password'])) {
                unset($data['password']);
            }
            $res = (new Riderlist())->allowfield(true)->save($data, ['id' => $data['id']]);
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Riderlist())->where('id', $id)->find();
            return view('', [
                'row' => $row
            ]);
        }
    }


    public function rider_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Riderlist();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->delete();
                (new RiderStreet())->where(['riderid' => $id])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function riderstreet()
    {
        if ($this->request->isAjax()) {
            $model = new RiderStreet();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['rider'])) {
                $where[] = ['rs.riderid', '=', $post['rider']];
            }
            if (!empty($post['title'])) {
                $where[] = ['r.mobile|r.name|r.cards', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['agentid'])) {
                $where[] = ['rs.agentid', '=', $post['agentid']];
            }
            if (!empty($post['status'])) {
                $where[] = ['r.status', '=', $post['status']];
            }
            if (!empty($post['street'])) {
                $where[] = ['rs.street', '=', $post['street']];
            } elseif (!empty($post['area'])) {
                $where[] = ['rs.area', '=', $post['area']];
            } elseif (!empty($post['city'])) {
                $where[] = ['rs.city', '=', $post['city']];
            } elseif (!empty($post['province'])) {
                $where[] = ['rs.province', '=', $post['province']];
            }
            $count = $model->alias('rs')->join('riderlist r', 'rs.riderid = r.id')->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->alias('rs')->join('riderlist r', 'rs.riderid = r.id')
                ->where($where)->order(["rs.id" => 'desc', 'rs.status' => 'asc'])->field('rs.*,r.mobile,r.name,r.cards,r.positive,r.negative')->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['agent_name'] = (new Agents())->where(['id' => $lists['agentid']])->value('nickname') ?? '';
                $address = getdrees($lists['street'], 2);
                $lists['province_text'] = $address['province'];
                $lists['city_text'] = $address['city'];
                $lists['area_text'] = $address['area'];
                $lists['street_text'] = $address['street'];
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'province' => (new Region())->where(['level' => 1])->select(),
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }


    public function riderstreet_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'riderid' => 'require',
                'street' => 'require',
                'agentid' => 'require',
            ], [
                'riderid.require' => '师傅不能为空',
                'street.require' => '街道不能为空',
                'agentid.require' => '街道不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            //查询负责区域是否已存在
            $riderstreet = (new RiderStreet())->where([
                'riderid' => $data['riderid'],
                'street' => $data['street']
            ])->find();
            //查询是否有当前街道添加权限
            $ishave = geauthagents($data['agentid'], $data['street'], 0, 0);
            if (empty($ishave) || $ishave == 1) {
                return json(['code' => 1, 'msg' => '操作失败,代理无该街道操作权限']);
            }
            $data['status'] = 2;
            if (!empty($riderstreet)) {
                $res = (new RiderStreet())->allowfield(true)->save($data, ['id' => $riderstreet['id']]);
            } else {
                $res = (new RiderStreet())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $row = [];
            $province = (new Region())->where(['level' => 1])->select();
            $rider = (new Riderlist())->field('id,name,mobile')->select();
            $riderid = $this->request->get('riderid/d', 0);
            if (!empty($riderid)) {
                $row['riderid'] = $riderid;
            }
            $agent = (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select();
            return view('', [
                'row' => $row,
                'province' => $province,
                'rider' => $rider,
                'agent' => $agent
            ]);
        }
    }

    public function riderstreet_edit2()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'riderid' => 'require',
                'street' => 'require'
            ], [
                'riderid.require' => '师傅不能为空',
                'street.require' => '街道不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if (count($data['street']) <= 0) {
                return json(['code' => 1, 'msg' => '请选择街道']);
            }
            try {

                foreach ($data['street'] as $street) {
                    //查询负责区域是否已存在
                    $riderstreet = (new RiderStreet())->where([
                        'riderid' => $data['riderid'],
                        'street' => $street
                    ])->find();
                    //查询是否有当前街道添加权限
                    $ishave = geauthagents($data['agentid'], $data['street'], 0, 0);
                    if (empty($ishave) || $ishave == 1) {
                        continue;
                    }
                    $geo = getdrees($street, 3);
                    if (!empty($riderstreet)) {
                        (new RiderStreet())->allowfield(true)->save([
                            'agentid' => $geo['agentid'],
                            'riderid' => $data['riderid'],
                            'province' => $geo['province'],
                            'city' => $geo['city'],
                            'area' => $geo['area'],
                            'street' => $geo['street'],
                            'status' => 2
                        ], ['id' => $riderstreet['id']]);
                    } else {
                        (new RiderStreet())->allowfield(true)->save([
                            'agentid' => $geo['agentid'],
                            'riderid' => $data['riderid'],
                            'province' => $geo['province'],
                            'city' => $geo['city'],
                            'area' => $geo['area'],
                            'street' => $geo['street'],
                            'status' => 2
                        ]);
                    }
                }
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'msg' => '操作成功']);
        } else {
            $row = [];
            $province = (new Region())->where(['level' => 1])->select();
            $rider = (new Riderlist())->field('id,name,mobile')->select();
            $riderid = $this->request->get('riderid/d', 0);
            if (!empty($riderid)) {
                $row['riderid'] = $riderid;
            }
            $agent = (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select();
            return view('', [
                'row' => $row,
                'province' => $province,
                'rider' => $rider,
                'agent' => $agent
            ]);
        }
    }

    public function riderstreet_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new RiderStreet();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function riderstreet_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        $status = input('status/d', 0);
        if (!empty($id) && !empty($field)) {
            if ($status != 2 && $status != 3) {
                return json(['code' => 1, 'data' => [], 'msg' => '操作状态错误，请刷新页面重试']);
            }
            $model = new RiderStreet();
            $cate = $model->where(['id' => $id])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'status':
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function product()
    {
        if ($this->request->isAjax()) {
            $model = new Product();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['isdel', '=', 1];
            $where[] = ['agentid', '>', 0];
            if (!empty($post['title'])) {
                $where[] = ['title', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['agentid'])) {
                $where[] = ['agentid', '=', $post['agentid']];
            }
            if (!empty($post['cate'])) {
                $where[] = ['cate', '=', $post['cate']];
            }
            if (!empty($post['subcate'])) {
                $where[] = ['subcate', '=', $post['subcate']];
            }
            if (!empty($post['isshow'])) {
                $where[] = ['isshow', '=', $post['isshow']];
            }
            if (!empty($post['ishot'])) {
                $where[] = ['ishot', '=', $post['ishot']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["sort" => "desc", "id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['agent_name'] = '系统';
                if ($lists['agentid'] > 0) {
                    $lists['agent_name'] = (new Agents())->where(['id' => $lists['agentid']])->value('nickname') ?? '';
                }
                $lists['type'] =  config()['config']['type'][$lists['type']];
                $lists['cate_name'] = (new Cate())->where(['id' => $lists['cate']])->value('name') ?? '无';
                $lists['subcate_name'] = (new Subcate())->where(['id' => $lists['subcate']])->value('name') ?? '无';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'cate' => (new Cate())->field('id,name,isshow')->order(['sort' => 'desc'])->select(),
                'subcate' => (new Subcate())->field('id,name,isshow')->order(['sort' => 'desc'])->select(),
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }


    public function product_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'agentid' => 'require',
                'cate' => 'require',
                'subcate' => 'require',
                'type' => 'require',
            ], [
                'title.require' => '标题不能为空',
                'agentid.require' => '代理不能为空',
                'cate.require' => '分类不能为空',
                'subcate.require' => '子分类不能为空',
                'type.require' => '类型不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if (!empty($data['id'])) {
                $res = (new Product())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new Product())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Product())->where('id', $id)->find();
            $subcate = [];
            if (empty($row)) {
                $agentid = $this->request->get('agentid/d', 0);
                $row['agentid'] = $agentid;
            } else {
                $where[] = ['cate', '=', $row['cate']];
                $where[] = ['agentid', '=', $row['agentid']];
                $subcate = (new Subcate())->where($where)->select();
            }
            return view('', [
                'row' => $row,
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select(),
                'cate' => (new Cate())->field('id,name,isshow')->order('sort desc')->select(),
                'subcate' => $subcate,
            ]);
        }
    }

    public function product_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        if (!empty($id) && !empty($field)) {
            $model = new Product();
            $cate = $model->where(['id' => $id])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'isshow':
                    $status = $cate['isshow'] == 1 ? 2 : 1;
                    break;
                case 'ishot':
                    $status = $cate['ishot'] == 1 ? 2 : 1;
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }


    public function product_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Product();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update(['isdel' => 2]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function subcate()
    {
        if ($this->request->isAjax()) {
            $model = new Subcate();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['name', 'like', '%' . $post['title'] . '%'];
            }
            $where[] = ['agentid', '>', 0];
            if (!empty($post['agentid'])) {
                $where[] = ['agentid', '=', $post['agentid']];
            }
            if (!empty($post['cate'])) {
                $where[] = ['cate', '=', $post['cate']];
            }
            if (!empty($post['isshow'])) {
                $where[] = ['isshow', '=', $post['isshow']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["sort" => "desc", "id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['agent_name'] = '系统';
                if ($lists['agentid'] > 0) {
                    $lists['agent_name'] = (new Agents())->where(['id' => $lists['agentid']])->value('nickname') ?? '';
                }
                $lists['cate_name'] = (new Cate())->where(['id' => $lists['cate']])->value('name') ?? '无';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'cate' => (new Cate())->field('id,name,isshow')->order(['sort' => 'desc'])->select(),
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }


    public function subcate_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'agentid' => 'require',
                'cate' => 'require'
            ], [
                'agentid.require' => '代理不能为空',
                'cate.require' => '类型不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $data['images'] = !empty($data['images']) ? $data['images'] : '';
            if (!empty($data['id'])) {
                $res = (new Subcate())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new Subcate())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Subcate())->where('id', $id)->find();
            if (empty($row)) {
                $agentid = $this->request->get('agentid/d', 0);
                $row['agentid'] = $agentid;
            }
            return view('', [
                'row' => $row,
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select(),
                'cate' => (new Cate())->field('id,name,isshow')->order('sort desc')->select(),
            ]);
        }
    }

    public function subcate_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        if (!empty($id) && !empty($field)) {
            $model = new Subcate();
            $cate = $model->where(['id' => $id])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'isshow':
                    $status = $cate['isshow'] == 1 ? 2 : 1;
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }



    public function subcate_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Subcate();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function agentlog()
    {
        if ($this->request->isAjax()) {
            $model = new AgentLog();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $agentid = input('agentid/d') ?? 0;
            $where = array();
            $where[] = ['user_id', '=', $agentid];
            if (!empty($post['types'])) {
                $where[] = ['types', '=', $post['types']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $model = new Agents();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['status', 'in', [1, 2]];
            if (!empty($post['title'])) {
                $where[] = ['accounts|nickname|mobile', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            if (!empty($post['type'])) {
                $wheres = array();
                $wheres[] = ['type', '=', $post['type']];
                switch ($post['type']) {
                    case '2':
                        if (!empty($post['city'])) {
                            $wheres[] = ['city', '=', $post['city']];
                        } elseif (!empty($post['province'])) {
                            $wheres[] = ['province', '=', $post['province']];
                        }
                        break;
                    case '3':
                        if (!empty($post['area'])) {
                            $wheres[] = ['area', '=', $post['area']];
                        } elseif (!empty($post['city'])) {
                            $wheres[] = ['city', '=', $post['city']];
                        } elseif (!empty($post['province'])) {
                            $wheres[] = ['province', '=', $post['province']];
                        }
                        break;
                    case '4':
                        if (!empty($post['street'])) {
                            $wheres[] = ['street', '=', $post['street']];
                        } elseif (!empty($post['area'])) {
                            $wheres[] = ['area', '=', $post['area']];
                        } elseif (!empty($post['city'])) {
                            $wheres[] = ['city', '=', $post['city']];
                        } elseif (!empty($post['province'])) {
                            $wheres[] = ['province', '=', $post['province']];
                        }
                        break;
                    default:
                        break;
                }
                $agents = (new AgentArea())->distinct(true)->where($wheres)->column('agentid');
                $where[] = ['id', 'in', $agents];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['product'] = (new Product())->where(['agentid' => $lists['id'], 'isdel' => 1])->count();
                $lists['btmoneys'] = (new Coupon())->where(['agentid' => $lists['id'], 'types' => 2, 'status' => 1, 'endstatus' => 1])->sum('btmoney'); //未使用
                $lists['btmoneys1'] = (new Coupon())->where(['agentid' => $lists['id'], 'types' => 2, 'status' => [1, 2], 'endstatus' => 2])->sum('btmoney'); //已使用
                $lists['btmoneys2'] = (new Coupon())->where(['agentid' => $lists['id'], 'types' => 2, 'status' => 2, 'endstatus' => 1])->sum('btmoney'); //使用中
                $lists['agentname'] = '无';
                if ($lists['top'] > 0) {
                    $agent = (new Agents())->where('id', $lists['top'])->find();
                    if (!empty($agent)) {
                        $lists['agentname'] = $agent['nickname'] . '(' . $agent['accounts'] . ')';
                    }
                }
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'province' => (new Region())->where(['level' => 1])->select(),
                'agent' => (new Agents())->select()

            ]);
        }
    }

    public function agent_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'nickname' => 'require|chsAlphaNum|length:4,50',
                'accounts' => 'require|alphaNum|length:6,50',
                'mobile' => 'require',
            ], [
                'nickname.require' => '备注不能为空',
                'nickname.length' => '备注长度控制在6-20个字符',
                'nickname.chsAlphaNum' => '备注只能是汉字、字母和数字',
                'accounts.require' => '账号不能为空',
                'accounts.alphaNum' => '账号只能是字母和数字',
                'accounts.length' => '账号长度控制在6-50个字符',
                'mobile.require' => '手机不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
                $this->result([], 1, '手机格式不正确');
            }
            if (!empty($post['top'])) {
                $where[] = ['top', '=', $post['top']];
            }
            if (empty($data['id']) && empty($data['password'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家密码必须填写']);
            }
            if (!empty($data['id']) && empty($data['password'])) {
                unset($data['password']);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            }
            $data['levelopen'] = $data['levelopen'] ?? 1;
            if ($data['levelopen'] == 2) {
                if ($data['levelrate'] < 1 || $data['levelrate'] > 100) {
                    return json(['code' => 1, 'data' => [], 'msg' => '折扣率范围不能低于1且不能超过100']);
                }
            }
            $model = new Agents();
            //查找店铺名称、账号是否已经被使用
            $haveshop = $model->where(['accounts' => $data['accounts'], 'status' => [1, 2]])->find();
            if (!empty($data['id'])) {
                if (!empty($haveshop) && $haveshop['id'] != $data['id']) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                if (!empty($haveshop)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                $res = $model->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Agents();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            $agent = (new Agents())->where('id', "<>", $id)->select();
            return view('', [
                'province' => (new Region())->where(['level' => 1])->select(),
                'agent' => $agent,
                'row' => $row
            ]);
        }
    }


    public function agent_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Agents();
            $areamodel = new AgentArea();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update(['status' => 3]);
                $areamodel->where(['agentid' => $id])->delete();
                (new RiderStreet())->where(['agentid' => $id])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }


    public function agent_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        if (!empty($id) && !empty($field)) {
            $model = new Agents();
            $agent = $model->where(['id' => $id])->find();
            if (empty($agent)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'status':
                    if ($agent['status'] == 3) {
                        return json(['code' => 1, 'data' => [], 'msg' => '账号已被删除']);
                    }
                    $status = $agent['status'] == 1 ? 2 : 1;
                    break;
                case 'openid':
                    $status = null;
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }


    public function agentarea()
    {

        if ($this->request->isAjax()) {
            $model = new AgentArea();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['accounts|nickname|mobile', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['agentid'])) {
                $where[] = ['agentid', '=', $post['agentid']];
            }
            if (!empty($post['type'])) {
                $where[] = ['type', '=', $post['type']];
                switch ($post['type']) {
                    case '2':
                        if (!empty($post['city'])) {
                            $where[] = ['city', '=', $post['city']];
                        } elseif (!empty($post['province'])) {
                            $where[] = ['province', '=', $post['province']];
                        }
                        break;
                    case '3':
                        if (!empty($post['area'])) {
                            $where[] = ['area', '=', $post['area']];
                        } elseif (!empty($post['city'])) {
                            $where[] = ['city', '=', $post['city']];
                        } elseif (!empty($post['province'])) {
                            $where[] = ['province', '=', $post['province']];
                        }
                        break;
                    case '4':
                        if (!empty($post['street'])) {
                            $where[] = ['street', '=', $post['street']];
                        } elseif (!empty($post['area'])) {
                            $where[] = ['area', '=', $post['area']];
                        } elseif (!empty($post['city'])) {
                            $where[] = ['city', '=', $post['city']];
                        } elseif (!empty($post['province'])) {
                            $where[] = ['province', '=', $post['province']];
                        }
                        break;
                    default:
                        break;
                }
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $row) {
                $row['agent_name'] = (new Agents())->where(['id' => $row['agentid']])->value('nickname') ?? '';
                $row['province_list'] = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->value('name') ?? '无';
                $row['city_list'] = (new Region())->where(['level' => 2, 'area_code' => $row['city']])->value('name') ?? '无';
                $row['area_list'] = (new Region())->where(['level' => 3, 'area_code' => $row['area']])->value('name') ?? '无';
                $row['street_list'] = (new Region())->where(['level' => 4, 'id' => $row['street']])->value('name') ?? '无';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'province' => (new Region())->where(['level' => 1])->select(),
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select(),
            ]);
        }
    }

    public function agentarea_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'agentid' => 'require',
                'type' => 'require|in:2,3,4,5'
            ], [
                'agentid.require' => '代理不能为空',
                'type.require' => '类型不能为空',
                'type.in' => '类型不正确'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            switch ($data['type']) {
                case '2':
                    if (empty($data['province'])) {
                        return json(['code' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['code' => 1, 'msg' => '请选择城市']);
                    }
                    //添加高级别需要删除低级别权限
                    $havearea = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => [3, 4], 'city' => $data['city']])->find();
                    if (!empty($havearea)) {
                        return json(['code' => 1, 'msg' => '添加或更改更高级别区域管理前请先确认并删除低级别区域管理权限']);
                    }
                    $data['area'] = 0;
                    $data['street'] = 0;
                    break;
                case '3':
                    if (empty($data['province'])) {
                        return json(['code' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['code' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['code' => 1, 'msg' => '请选择区域']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 2, 'city' => $data['city']])->find();
                    if (!empty($haveareat)) {
                        return json(['code' => 1, 'msg' => '您已拥有高级别的城市管理，无需再添加低级别城市管理']);
                    }
                    //添加高级别需要删除低级别权限
                    $havearea = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 4, 'area' => $data['area']])->find();
                    if (!empty($havearea)) {
                        return json(['code' => 1, 'msg' => '添加或更改更高级别区域管理前请先确认并删除低级别区域管理权限']);
                    }
                    $data['street'] = 0;
                    break;
                case '4':
                    if (empty($data['province'])) {
                        return json(['code' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['code' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['code' => 1, 'msg' => '请选择区域']);
                    }
                    if (empty($data['street'])) {
                        return json(['code' => 1, 'msg' => '请选择街道']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 2, 'city' => $data['city']])->find();
                    if (!empty($haveareat)) {
                        return json(['code' => 1, 'msg' => '您已拥有高级别的城市管理，无需再添加低级别城市管理']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat2 = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 3, 'area' => $data['area']])->find();
                    if (!empty($haveareat2)) {
                        return json(['code' => 1, 'msg' => '您已拥有高级别的区域管理，无需再添加低级别区域管理']);
                    }
                    break;
                case '5':
                    if (empty($data['province'])) {
                        return json(['code' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['code' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['code' => 1, 'msg' => '请选择区域']);
                    }
                    if (empty($data['street'])) {
                        return json(['code' => 1, 'msg' => '请选择街道']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 2, 'city' => $data['city']])->find();
                    if (!empty($haveareat)) {
                        return json(['code' => 1, 'msg' => '您已拥有高级别的城市管理，无需再添加低级别城市管理']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat2 = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 3, 'area' => $data['area']])->find();
                    if (!empty($haveareat2)) {
                        return json(['code' => 1, 'msg' => '您已拥有高级别的区域管理，无需再添加低级别区域管理']);
                    }
                    break;
                default:
                    return json(['code' => 1, 'msg' => '代理区域类型错误']);
                    break;
            }
            if ($data['type'] != 5) {
                //查询负责区域是否已存在
                $businessarea = (new AgentArea())->where([
                    'type' => $data['type'],
                    'province' => $data['province'],
                    'city' => $data['city'],
                    'area' => $data['area'],
                    'street' => $data['street']
                ])->find();
                if (!empty($businessarea)) {
                    return json(['code' => 1, 'msg' => '管理区域已添加或已分配']);
                }
            }
            $res = (new AgentArea())->allowfield(true)->save($data);
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new AgentArea())->where('id', $id)->find();
            $province = (new Region())->where(['level' => 1])->select();
            $city = [];
            $area = [];
            $street = [];
            $agent = (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select();
            if (empty($row)) {
                $agentid = $this->request->get('agentid/d', 0);
                if (!empty($agentid)) {
                    $row['agentid'] = $agentid;
                }
            }
            return view('', [
                'row' => $row,
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'street' => $street,
                'agent' => $agent
            ]);
        }
    }

    public function agentarea_edit2()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'agentid' => 'require',
                'type' => 'require|in:2,3,4'
            ], [
                'agentid.require' => '代理不能为空',
                'type.require' => '类型不能为空',
                'type.in' => '类型不正确'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $saveAll = [];
            switch ($data['type']) {
                case '2':
                    if (empty($data['province'])) {
                        return json(['code' => 1, 'msg' => '请选择省份']);
                    }
                    if (!is_array($data['city'])) {
                        return json(['code' => 1, 'msg' => '城市参数错误，请重新选择或联系管理员']);
                    }
                    if (count($data['city']) <= 0) {
                        return json(['code' => 1, 'msg' => '请选择城市']);
                    }
                    //添加高级别需要删除低级别权限
                    $havearea = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => [3, 4], 'city' => $data['city']])->find();
                    if (!empty($havearea)) {
                        return json(['code' => 1, 'msg' => '存在当前添加区域低级权限，请先删除']);
                    }
                    foreach ($data['city'] as $city) {
                        //查询负责区域是否已存在
                        $haves = (new AgentArea())->where([
                            'type' => $data['type'],
                            'city' => $city
                        ])->find();
                        if (!empty($haves) && $haves['agentid'] != $data['agentid']) {
                            $city = (new Region())->where(['level' => 2, 'area_code' => $city])->value('name');
                            return json(['code' => 1, 'msg' => $city . '当前区域已分配']);
                        }
                        if (empty($haves)) {
                            $saveAll[] = [
                                'type' => $data['type'],
                                'province' => $data['province'],
                                'city' => $city,
                                'area' => 0,
                                'street' => 0,
                                'agentid' => $data['agentid']
                            ];
                        }
                    }
                    break;
                case '3':
                    if (empty($data['province'])) {
                        return json(['code' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city']) || is_array($data['city'])) {
                        return json(['code' => 1, 'msg' => '请选择城市或城市参数错误']);
                    }
                    if (count($data['area']) <= 0) {
                        return json(['code' => 1, 'msg' => '请选择区域']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 2, 'city' => $data['city']])->find();
                    if (!empty($haveareat)) {
                        return json(['code' => 1, 'msg' => '您已拥有当前区域高级别的管理权限']);
                    }
                    //添加高级别需要删除低级别权限
                    $havearea = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 4, 'area' => $data['area']])->find();
                    if (!empty($havearea)) {
                        return json(['code' => 1, 'msg' => '存在当前添加区域低级权限，请先删除']);
                    }
                    foreach ($data['area'] as $area) {
                        //查询负责区域是否已存在
                        $haves = (new AgentArea())->where([
                            'type' => $data['type'],
                            'area' => $area
                        ])->find();
                        if (!empty($haves) && $haves['agentid'] != $data['agentid']) {
                            $area = (new Region())->where(['level' => 3, 'area_code' => $area])->value('name');
                            return json(['code' => 1, 'msg' => $area . '当前区域已分配']);
                        }
                        if (empty($haves)) {
                            $saveAll[] = [
                                'type' => $data['type'],
                                'province' => $data['province'],
                                'city' => $data['city'],
                                'area' => $area,
                                'street' => 0,
                                'agentid' => $data['agentid']
                            ];
                        }
                    }
                    break;
                case '4':
                    if (empty($data['province'])) {
                        return json(['code' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city']) || is_array($data['city'])) {
                        return json(['code' => 1, 'msg' => '请选择城市或城市参数错误']);
                    }
                    if (empty($data['area']) || is_array($data['area'])) {
                        return json(['code' => 1, 'msg' => '请选择区域']);
                    }
                    if (count($data['street']) <= 0) {
                        return json(['code' => 1, 'msg' => '请选择街道']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 2, 'city' => $data['city']])->find();
                    if (!empty($haveareat)) {
                        return json(['code' => 1, 'msg' => '您已拥有当前区域高级别的管理权限']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat2 = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 3, 'area' => $data['area']])->find();
                    if (!empty($haveareat2)) {
                        return json(['code' => 1, 'msg' => '您已拥有当前区域高级别的管理权限']);
                    }
                    foreach ($data['street'] as $street) {
                        //查询负责区域是否已存在
                        $haves = (new AgentArea())->where([
                            'type' => $data['type'],
                            'street' => $street
                        ])->find();
                        if (!empty($haves) && $haves['agentid'] != $data['agentid']) {
                            $street = (new Region())->where(['level' => 3, 'id' => $street])->value('name');
                            return json(['code' => 1, 'msg' => $street . '当前区域已分配']);
                        }
                        if (empty($haves)) {
                            $saveAll[] = [
                                'type' => $data['type'],
                                'province' => $data['province'],
                                'city' => $data['city'],
                                'area' => $data['area'],
                                'street' => $street,
                                'agentid' => $data['agentid']
                            ];
                        }
                    }
                    break;
                default:
                    return json(['code' => 1, 'msg' => '代理区域类型错误']);
                    break;
            }
            if (count($saveAll) <= 0) {
                return json(['code' => 200, 'msg' => '操作成功,请查看检查']);
            }
            $res = (new AgentArea())->allowfield(true)->saveAll($saveAll);
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new AgentArea())->where('id', $id)->find();
            $province = (new Region())->where(['level' => 1])->select();
            $city = [];
            $area = [];
            $street = [];
            $agent = (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select();
            if (empty($row)) {
                $agentid = $this->request->get('agentid/d', 0);
                if (!empty($agentid)) {
                    $row['agentid'] = $agentid;
                }
            }
            return view('', [
                'row' => $row,
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'street' => $street,
                'agent' => $agent
            ]);
        }
    }


    public function agentarea_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new AgentArea();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function money_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'moneys' => 'require|gt:0',
                'type' => 'require|in:1,2',
                'id' => 'require',
                'types' => 'require|in:1,2',
            ], [
                'id.require' => 'ID不能为空',
                'type.require' => '操作类型不能为空',
                'type.in' => '操作类型不正确',
                'moneys.require' => '金额不能为空',
                'moneys.gt' => '金额必须大于0',
                'types.require' => '钱包种类不能为空',
                'types.in' => '钱包种类不正确',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $data['desc'] = empty($data['desc']) ? '资产变更' : $data['desc'];
            if ($data['type'] == 1) {
                $money = abs($data['moneys']);
            } else {
                $money = -abs($data['moneys']);
            }
            Db::startTrans();
            try {
                if ($data['types'] == 1) {
                    (new Agents())->MoneyEdit($data['id'], 4, $money, $data['desc'], 0);
                } else {
                    (new Agents())->MoneyEdit2($data['id'], 4, $money, $data['desc'], 0);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
    }
}
